package com.dm.frontend.interceptors;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginSessionInterceptor implements HandlerInterceptor {

    // 前置处理
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();

        System.out.println(requestURI);
        if(requestURI.startsWith("/admin/")
                && !requestURI.equals("/to/login")
                && !requestURI.equals("/login")){
            // 检查是否有用户存在
            Object user = request.getSession().getAttribute("user");
            if(user == null){
                System.out.println("===");
                response.sendRedirect("/to/login");
                return false;

            }

        }
        return true;
    }

    // 提交处理
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    // 后置处理
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
